package com.blogsystem.config;

import org.apache.catalina.filters.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * 安全配置类，用于定义Spring Security的过滤器链和密码编码器
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 启用方法级安全注解
public class SecurityConfig {
    @Autowired
    private CustomAuthentication customAuthentication;


    /**
     * 配置安全过滤器链
     *
     * @param http HttpSecurity对象，用于构建安全配置
     * @return 构建好的SecurityFilterChain对象
     * @throws Exception 如果构建过程中发生异常
     */

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
//                // 启用CSRF保护（使用Session存储）
//                .csrf(csrf -> csrf
//                        .csrfTokenRepository(new HttpSessionCsrfTokenRepository())
//                )



                // 禁用默认的CSRF保护（生产环境建议启用）
                .csrf(csrf -> csrf.disable())

                // 配置请求授权规则
                .authorizeHttpRequests(auth -> auth
                        // 允许匿名访问的路径
                        .requestMatchers(
                                "/", "/index", "/login", "/register",
                                "/css/**", "/js/**",
                                "/api/auth/register","/user/**","/image/**"
                                ,"logout",  "/api/article/**", "/api/auth/logout/**"
                        ).permitAll()
                        .requestMatchers("/api/admin/**").hasRole("ADMIN") // 限制/admin路径下所有资源仅管理员访问
                        .anyRequest().authenticated() // 其他请求也需要认证
                )
                // 配置表单登录
                .formLogin(form -> form
                        // 自定义登录页面
                        .loginPage("/login")
                        // 明确指定登录处理URL
                        .loginProcessingUrl("/login")
                        // 登录成功后跳转到首页
//                       .successHandler(customAuthentication)
                        .defaultSuccessUrl("/", true)
                        // 登录失败跳转回登录页并携带错误参数
                        .failureUrl("/login?error=true")
                        // 登录页允许匿名访问
                        .permitAll()

                )
                // 配置退出登录
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")) // 允许 GET 请求退出
                        .logoutSuccessUrl("/index")  // 成功登出后跳转到首页
                        .addLogoutHandler((request, response, authentication) -> {
                            // 可以在这里添加一些自定义清理逻辑（可选）
                        })
                        .permitAll()
                );

        return http.build();
    }

    /**
     * 提供认证管理器 Bean
     */
    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 提供密码编码器 Bean，使用 BCrypt 算法进行密码加密
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCryptPasswordEncoder 进行密码加密
        return new BCryptPasswordEncoder();
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://yourdomain.com")); // 替换为你的域名
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}